package io.geekidea.boot.test.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.geekidea.boot.framework.exception.BusinessException;
import io.geekidea.boot.framework.page.OrderByItem;
import io.geekidea.boot.framework.page.OrderMapping;
import io.geekidea.boot.framework.page.Paging;
import io.geekidea.boot.test.dto.CardDto;
import io.geekidea.boot.test.entity.Card;
import io.geekidea.boot.test.mapper.CardMapper;
import io.geekidea.boot.test.query.CardQuery;
import io.geekidea.boot.test.service.CardService;
import io.geekidea.boot.test.vo.CardVo;
import io.geekidea.boot.test.query.AppCardQuery;
import io.geekidea.boot.test.vo.AppCardVo;
import io.geekidea.boot.util.PagingUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.List;

/**
 * 卡片 服务实现类
 *
 * @author geekidea
 * @since 2025-03-26
 */
@Slf4j
@Service
public class CardServiceImpl extends ServiceImpl<CardMapper, Card> implements CardService {

    @Autowired
    private CardMapper cardMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean addCard(CardDto dto) {
        Card card = new Card();
        BeanUtils.copyProperties(dto, card);
        return save(card);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateCard(CardDto dto) {
        Long id = dto.getId();
        Card card = getById(id);
        if (card == null) {
            throw new BusinessException("卡片不存在");
        }
        BeanUtils.copyProperties(dto, card);
        return updateById(card);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteCard(Long id) {
        return removeById(id);
    }

    @Override
    public CardVo getCardById(Long id) {
        return cardMapper.getCardById(id);
    }

    @Override
    public Paging<CardVo> getCardPage(CardQuery query) {
        OrderMapping orderMapping = new OrderMapping();
        orderMapping.put("createTime", "create_time");
        PagingUtil.handlePage(query, orderMapping, OrderByItem.desc("id"));
        List<CardVo> list = cardMapper.getCardPage(query);
        Paging<CardVo> paging = new Paging<>(list);
        return paging;
    }

    @Override
    public AppCardVo getAppCardById(Long id) {
        return cardMapper.getAppCardById(id);
    }

    @Override
    public Paging<AppCardVo> getAppCardPage(AppCardQuery query) {
        OrderMapping orderMapping = new OrderMapping();
        orderMapping.put("createTime", "create_time");
        PagingUtil.handlePage(query, orderMapping, OrderByItem.desc("id"));
        List<AppCardVo> list = cardMapper.getAppCardPage(query);
        Paging<AppCardVo> paging = new Paging<>(list);
        return paging;
    }

}
